package com.lxj.common.handler;

import com.lxj.common.CodeMsg;
import com.lxj.common.Result;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lxj
 * @date 2021/6/16 18:46
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理Shiro的登录异常
     * @param shiroException
     * @return
     */
    @ExceptionHandler
    @ResponseBody
    public Result loginException(ShiroException shiroException) {
        //处理登录的错误
        if (shiroException instanceof AuthenticationException) {
            return new Result(CodeMsg.USER_USER_PASSWORD_ERROR);
        }
        //处理没有权限的错误
        if (shiroException instanceof UnauthorizedException) {
            return new Result(CodeMsg.USER_IS_NOT_ROLE);
        }
        return new Result(CodeMsg.ERROR);
    }

    /**
     * 处理验证码错误的异常
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handlerIllegalArgumentException() {
        return new Result(CodeMsg.USER_CODE_ERROR);
    }
}
